/**
 * Created by yzl on 2017/9/26.
 */
//全局禁用路由
$.config = {router: false}
//固定定位
var eFixedFn = function (ele) {
    var ele = $(ele),
        stop = ele.offset().top,
        sFn = function () {
            var t = $('.content').scrollTop();
            if(t > (stop-50)) {
                ele.children().addClass('b-fixed')
            } else {
                ele.children().removeClass('b-fixed')
            }
        };
    document.querySelector('.content').addEventListener('scroll', function () {
        sFn();
    });
};

//向上滚动方法
var upScroll = function (op) {
    var _upWrap = $(op),
        _mli = _upWrap.find("li")

    if(_mli.length <= 1) return
    new Swiper(op, {
        direction:'vertical',
        loop: true,
        autoplay: 5000,
        autoplayDisableOnInteraction: false
    })
}

//禁止ios浏览器页面上下滚动 (橡皮筋效果)
function iosTrouchFn(element) {
    var isIosFlag = navigator.userAgent.indexOf('iphone'),
        overscroll = function(el) {
            el.addEventListener('touchstart', function() {
                var top = el.scrollTop,
                    totalScroll = el.scrollHeight,
                    currentScroll = top + el.offsetHeight;
                if(top === 0) {
                    el.scrollTop = 1;
                }else if(currentScroll === totalScroll) {
                    el.scrollTop = top - 1;
                }
            });
            el.addEventListener('touchmove', function(evt) {
                if(el.offsetHeight < el.scrollHeight)
                    evt._isScroller = true;
            });
        }

    if(isIosFlag === -1) {
        overscroll(element)
        document.body.addEventListener('touchmove', function(evt) {
            if(!evt._isScroller) {
                evt.preventDefault();
            }
        });
    }
}

//底部公共菜单选中方法
function currBottomMenuOption() {
    //包含选中的页面
    var menuLinkArr = [
        ['/index','/uc/course/myCourse'],
        ['/course/courseList','/teacher/teacherList','/course/recommend/index','/course/classify/index'],
        ['/exam/examIndex','/uc/exam/record/history'],
        ['/class/index','/uc/class/personal/index','/uc/topic/personal/index'],
        ['/uc/index']
    ];
    var localHref = location.href.split("mobile"),
        currHref = '';
    if(localHref[1].indexOf("?") !== -1){//有参数
        currHref = localHref[1].split("?");
        currHref = localHref[0];
    }else {//没有参数
        currHref = localHref[1];
    }
    menuLinkArr.filter(function (item,inx) {
        if(item.indexOf(currHref) !== -1) {
            $("#bcMenu_" + (inx+1)).addClass("active").siblings().removeClass("active")
        }
    })
}

/**
 * 获取专业数据
 * @param parentId
 */
function findSubjectList(callback) {
    var params = {};
    params = JSON.stringify(params);
    $.ajax({
        url:baseloaction +'/mobile/subject/ajax/findLayeredSubjectList',
        data: params,
        type:'post',
        dataType:'json',
        contentType: 'application/json;charset=utf-8',
        success:function (result) {
            if(result.success==true){
                if($.isFunction(callback)){
                    callback(result.entity);
                }
            }else{
                $.toast(result.message);
            }
        },
        error:function (error) {
            $.toast('系统错误，专业数据获取失败');
        }
    });
}


var SESSIONSTORAGE = sessionStorage
var isEmpty = function (str) {
    if (str === null || typeof str === 'undefined' || str === '') {
        return true
    }
    return false
}
var _setSessionStorage = function (key, value) {
    if (isEmpty(key)) {
        return console.error('ReferenceError: key in set is not defined')
    }

    if (value instanceof Object) {
        value = JSON.stringify(value)
    }
    SESSIONSTORAGE[key] = value
    return SESSIONSTORAGE
}
var _getSessionStorage = function (key) {
    if (isEmpty(key)) {
        return console.error('ReferenceError: key in get is not defined')
    }

    var value = SESSIONSTORAGE[key]

    try {
        value = JSON.parse(value)
    } catch (error) {}

    return value
}
var _removeSessionStorage = function (key) {
    if (isEmpty(key)) {
        return SESSIONSTORAGE.clear()
    } else {
        return SESSIONSTORAGE.removeItem(key)
    }
}
//初始化图片上传
function initUpdate(obj) {
    var uploader = WebUploader.create({
        //是否是自动上传
        server:staticPath+'/image/upload/file',
        method:'POST',
        //指定选择文件的按钮容器，不指定则不创建按钮
        pick: {
            //指定选择文件的按钮容器，不指定则不创建按钮。注意 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点
            id: '#'+obj.id,
            label: 'ddd',
            //指定按钮文字。不指定时优先从指定的容器中看是否自带文字
            innerHTML: '<span class="icon icon-picture vam"></span> 选择图片',
            //是否开起同时选择多个文件能力
            multiple:true
        },
        //服务文件名
        fileVal:'fileupload',
        //参数
        formData:obj.formData,
        //最大允许多少个文件
        fileNumLimit:obj.fileNumLimit?obj.fileNumLimit:1,
        //文件总大小
        fileSizeLimit:1024*1024*10,
        //单个文件最大限制2M
        fileSingleSizeLimit:1024*1024*2,
        //对图片不进行压缩
        compress:false
    });
    //发送错误
    uploader.on('error',function (code) {
        if(code=='F_DUPLICATE'){
            $.toast("选择的文件已存在队列中");
        }else if(code=='Q_EXCEED_NUM_LIMIT'){
            $.toast("一次最多可上传"+(obj.fileNumLimit?obj.fileNumLimit:1)+"个文件");
        }else if(code=='Q_EXCEED_SIZE_LIMIT'){
            $.toast("总文件大小已到最大限额");
        }else if(code=='Q_TYPE_DENIED'){
            $.toast("文件类型错误");
        }else if(code=='F_EXCEED_SIZE'){
            $.toast("文件过大，最大可传2M");
        }else{
            $.toast("添加文件失败");
        }
    });
    //当文件被加入队列以后触发
    uploader.on('fileQueued',function (file) {
        //生成文件预览
        if($.isFunction(obj.makeThumb)){
            uploader.makeThumb( file, function( error, ret ) {
                obj.makeThumb(error,file,ret);
            });
        }
    });
    //当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效
    uploader.on('uploadAccept',function (object,ret) {

    });
    //当文件上传成功时触发。
    uploader.on('uploadSuccess',function (file,response) {
        if(response.success==true){
            var entity = response.entity;
            var url = entity.url;
            var successUrlList = uploader.successUrlList;
            if(typeof successUrlList =='undefined' || $.isEmptyObject(successUrlList)){
                successUrlList = new Array();
            }
            successUrlList.push(url);
            uploader.successUrlList = successUrlList;
        }
    });
    //当所有文件上传结束时触发
    uploader.on('uploadFinished',function () {
        if($.isFunction(obj.success)){
            obj.success(uploader.successUrlList);
            delete uploader.successUrlList;
            delete uploader.fileList;
        }
    });
    //上传过程中触发，携带上传进度
    uploader.on('uploadProgress',function (file,percentage ) {

    });
    //返回上传对象
    return uploader;
}

function lazyloadImage() {
    //懒加载
    new wLazyload({
        errorImage : staticPath+'/front/mobile/v3/img/default/error-pic.jpg', //图片加载失败占位图
        scrollEle : document.querySelector('.content') //滚动节点对象，默认为 window
    });
}


function getParameter(name) {
    var url = document.location.href;
    var start = url.indexOf("?")+1;
    if (start==0) {
        return "";
    }
    var value = "";
    var queryString = url.substring(start);
    var paraNames = queryString.split("&");
    for (var i=0; i<paraNames.length; i++) {
        if (name==getParameterName(paraNames[i])) {
            value = getParameterValue(paraNames[i])
        }
    }
    return value;
}
function getParameterName(str) {
    var start = str.indexOf("=");
    if (start==-1) {
        return str;
    }
    return str.substring(0,start);
}

function getParameterValue(str) {
    var start = str.indexOf("=");
    if (start==-1) {
        return "";
    }
    return str.substring(start+1);
}


// 图片放大 查看器
function openPhotoBrowser(that,imgs) {
    var imagres = [];
    //第一张图片的dom
    imagres[0] = that.attr('src');
    if (imgs!=null&&imgs.length>0) {
        $.each(imgs, function (i, val) {
            var img = $(val).attr('src');
            //将其他图片放入数组中
            if (img != imagres[0]) {
                imagres[i + 1] = img;
            }
        });
    }
    $.photoBrowser({
        photos: imagres,
        type: 'popup'
    }).open();

};

//对溢出的文字进行折叠处理
//teacher class info more
function textInfoMore() {
    var _teacherBox = $('.teacher-info-box').height(),
        _teacherIner = $('.teacher-info-box > span.wm-txt-small').height(),
        flag = true

    if(_teacherIner > _teacherBox) {
        $('.teacher-info-more-btn').show().on('click', function () {
            if(flag) {
                $('.teacher-info-box').css('max-height', 'inherit')
                $(this).text('[收起...]')
                flag = false
            } else {
                $('.teacher-info-box').css('max-height', '3rem')
                $(this).text('[更多...]')
                flag = true
            }
        })
    } else {
        $('.teacher-info-more-btn').hide()
    }
}


//判断是否是微信浏览器的函数
function isWeiXin(){
    //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息
    //通过正则表达式匹配ua中是否含有MicroMessenger字符串
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

//修正文本输入框在微信环境下iOS机型部分不容易获取焦点
$(function () {
    if(isWeiXin() && $.device.ios) {
        $('body').on('click', 'input', function () {
            $(this).focus()
        })
    }
});

//验证当前分享显示按钮(因为后台配置不完善目前只判断海报分享按钮)
function checkBaseShare(shareChannel) {
    if (shareChannel.indexOf(6) != -1){
        return '2 4'
    } else {
        return '2 3 4'
    }
}

//公共积分获取提示层
var getIntegralModalFn = function (msg) {
    var _ele = '<div class="getIntegralModal"><span class="getIntegralIcon"></span><div class="fs7 c-e2">'+ msg +'</div></div>'
    $.toast(_ele, 5000)
}

//日期格式化
function dateFormat(fmt, date) {
    var ret;
    var opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], formatNumber(opt[k]))
        };
    };
    return fmt;
}

 var formatNumber = function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}


//计算时间
function getBeforeDate(date,days){
    date.setDate(date.getDate()+days);
    return date;
}

/**
 *
 * 获取当前日期一周的时间
 */
function getWeekDay(newDate) {
    var new_Date = newDate
    var timesStamp = new_Date.getTime();
    var currenDay = new_Date.getDay();
    var dates = [];
    for(var i = 0; i < 7; i++) {
        dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)));
    }
    return dates
}
//获取区间内的值
function getDiffDate(start, end) {

    var startTime =  start;

    var endTime = end;

    var dateArr = [];

    while ((endTime.getTime() - startTime.getTime()) > 0) {

        var year = startTime.getFullYear();

        var month = startTime.getMonth().toString().length === 1 ? "0" + (parseInt(startTime.getMonth().toString(),10) + 1) : (startTime.getMonth() + 1);

        var day = startTime.getDate().toString().length === 1 ? "0" + startTime.getDate() : startTime.getDate();

        dateArr.push(year + "-" + month + "-" + day);

        startTime.setDate(startTime.getDate() + 1);

    }

    return dateArr;

}



function getDate (dateString) {
    if (dateString) {
        var date = new Date(dateString.replace(/-/, "/"))
        return date;
    }
}


function getBeforeWeekDay() {
    var myDate = new Date(new Date().getTime() - 7 * 24 * 3600 * 1000)
    var day = myDate.getDay()
    var time = myDate.getDate() - day + (day === 0 ? -6 : 1)
    var startTime = new Date(myDate.setDate(time))

    var endTime = new Date(myDate.setDate(time + 6))

    return {startTime:startTime,endTime:endTime};
}


/**
 * 当前月的最后一天和最后一个月
 * @returns {{startTime: string, endTime: string}}
 */
function getFrsitMonthandLast(firstDate) {
    var nowDate = firstDate;
    var cloneNowDate = firstDate;
    var fullYear = nowDate.getFullYear();
    var month = nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月
    var endOfMonth = new Date(fullYear, month, 0).getDate(); // 获取本月最后一天
    function getFullDate(targetDate) {
        var D, y, m, d;
        if (targetDate) {
            D = new Date(targetDate);
            y = D.getFullYear();
            m = D.getMonth() + 1;
            d = D.getDate();
        } else {
            y = fullYear;
            m = month;
            d = date;
        }
        m = m > 9 ? m : '0' + m;
        d = d > 9 ? d : '0' + d;
        return y + '/' + m + '/' + d;


    };

    var endDate = getFullDate(cloneNowDate.setDate(endOfMonth));//当月最后一天
    var starDate = getFullDate(cloneNowDate.setDate(1));//当月第一天
    return {startTime:starDate,endTime:endDate};
}

var LOCALSTORAGE = localStorage
var isEmpty = function (str) {
    if (str === null || typeof str === 'undefined' || str === '') {
        return true
    }
    return false
}
var _setLOCALSTORAGE = function (key, value) {
    if (isEmpty(key)) {
        return console.error('ReferenceError: key in set is not defined')
    }
    if (value instanceof Object) {
        value = JSON.stringify(value)
    }
    LOCALSTORAGE[key] = value
    return LOCALSTORAGE
}
var _getLOCALSTORAGE = function (key) {
    if (isEmpty(key)) {
        return console.error('ReferenceError: key in get is not defined')
    }
    var value = LOCALSTORAGE[key]
    try {
        value = JSON.parse(value)
    } catch (error) {}
    return value
}
var _removeLOCALSTORAGE = function (key) {
    if (isEmpty(key)) {
        return LOCALSTORAGE.clear()
    } else {
        return LOCALSTORAGE.removeItem(key)
    }
}





